package com.jh3502.helper.function.person.personlist;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jh3502.helper.R;
import com.jh3502.helper.base.BaseActivity;
import com.jh3502.helper.function.batch.batchnew.BatchNewAdapter;
import com.jh3502.helper.function.batch.batchnew.BatchNewBean;
import com.jh3502.helper.utils.Constant;
import com.jh3502.helper.utils.ExcelUtil;
import com.jh3502.helper.utils.PinyinUtil;
import com.jh3502.helper.utils.SpHelper;
import com.jh3502.helper.utils.Utils;
import com.jh3502.helper.view.ActionSheetDialog;
import com.jh3502.helper.view.MyRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * author:harisucici on 2018/8/10 12:22
 * email:harisucici@gmail.com
 * name:
 * todo:
 */
public class PersonListFragment extends BaseActivity {
    @BindView(R.id.person_list_recycler)
    MyRecyclerView personListRecycler;
    @BindView(R.id.person_list_total)
    TextView personListTotal;
    @BindView(R.id.person_list_chosen_normal)
    RecyclerView personListChosenNormal;
    @BindView(R.id.person_list_chosen_sp)
    RecyclerView personListChosenSp;
    @BindView(R.id.person_list_num)
    EditText personListNum;
    @BindView(R.id.person_list_area)
    EditText personListArea;
    @BindView(R.id.person_list_name)
    EditText personListName;
    @BindView(R.id.person_list_person_num)
    EditText personListPersonNum;
    @BindView(R.id.person_list_date)
    EditText personListDate;
    @BindView(R.id.person_list_list_source)
    RadioGroup personListListSource;
    @BindView(R.id.dialog_add_num)
    EditText dialogAddNum;
    @BindView(R.id.dialog_add_num_del)
    ImageView dialogAddNumDel;
    @BindView(R.id.dialog_add_name)
    EditText dialogAddName;
    @BindView(R.id.dialog_add_name_del)
    ImageView dialogAddNameDel;
    @BindView(R.id.dialog_add_dep)
    TextView dialogAddDep;
    @BindView(R.id.dialog_add_sex)
    TextView dialogAddSex;
    @BindView(R.id.dialog_add)
    View dialogAdd;
    @BindView(R.id.dialog_warning)
    View dialogWarning;
    @BindView(R.id.person_list_check_normal)
    CheckBox personListCheckNormal;
    @BindView(R.id.person_list_check_sp)
    CheckBox personListCheckSp;
    private PersonListAdapter mAdapter;
    private Set<String> orgKey, depKey;
    @NonNull
    private List<PersonListBean> msg = new ArrayList<>(2);
    private String batchNo;
    private String batchTitle;
    //    private String[] selectOnline = {"全部", "已量体", "未量体"};
    private String[] selectSex = {"男", "女"};
    @NonNull
    private String[] setNew = {"新建", "导入"};
    private Map<String, Object> params;
    private String maleID, femaleID;
    private int[] mustContain = {0, 3, 4, 8, 9, 10, 14};
    private BatchNewAdapter batchNewUp, batchNewDown;
    @NonNull
    private List<BatchNewBean> batchUpList = new ArrayList<>();
    @NonNull
    private List<BatchNewBean> batchDownList = new ArrayList<>();
    @NonNull
    private List<Integer> batchUpListResult = new ArrayList<>();
    @NonNull
    private List<Integer> batchDownListResult = new ArrayList<>();
    @NonNull
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message message) {
            super.handleMessage(message);
            if (message.what == Constant.STATUS_SUCCESS) {
                if ("所有".equals(message.obj)) {
                    msg.clear();
                    msg.addAll(SpHelper.getInstance().getPersonList(batchNo));
//                    Collections.sort(msg);
                    mAdapter.notifyDataSetChanged();
                    return;
                }
                List<PersonListBean> beans = new ArrayList<>(2);
                String pinyin = PinyinUtil.getInstance().getPinyin(((String) message.obj).substring(0, 2));
                for (PersonListBean personListBean : SpHelper.getInstance().getPersonList(batchNo)) {
                    if (pinyin.equals(personListBean.getNamePinyin())) {
                        beans.add(personListBean);
                    }
                }
                if (beans.size() == 0) {
                    showShortToast("没有查到");
                    return;
                }
                if (beans.size() == 1) {
                    PersonListBean personListBean = msg.get(0);
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", Constant.PERSON_DETAIL_ACTIVITY);
                    bundle.putString("batchNo", batchNo);
                    bundle.putString("batchTitle", batchTitle);
                    bundle.putString("pno", personListBean.getPno());
                    bundle.putString("type", personListBean.getPno());
//                    bundle.putString("title", toolbarTitle.getText().toString());
//                    Utils.getInstance().startActivity(PersonListActivity.this, PersonNewActivity.class, bundle);
                }
                if (beans.size() > 1) {
                    msg.clear();
                    msg.addAll(beans);
//                    Collections.sort(msg);
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    };
    private int dialogAddSexId;

    @Override
    protected int setViewId() {
        return R.layout.fragment_person_list;
    }

    @Override
    protected void initView() {
        // left
        Map<String, Object> batInfo = Utils.getInstance().jso2map(SpHelper.getInstance().getBatAct());
        Log.e("3502", batInfo.toString());
        batchNo = (String) batInfo.get("batno");
        batchTitle = (String) batInfo.get("title");

        maleID = (String) batInfo.get("maleID");
        femaleID = (String) batInfo.get("femaleID");
//        ArrayList<Map<String, Object>> ruleList = Utils.getInstance().jsa2list(SpHelper.getInstance().getListltruleMale());
        mAdapter = new PersonListAdapter(this, msg);
        personListRecycler.setAdapter(mAdapter);
//        mAdapter.setOnItemClickListener(s -> {
//            PersonListBean personListBean = msg.get(Integer.parseInt(s));
//            Bundle bundle = new Bundle();
//            bundle.putInt("type", Constant.PERSON_DETAIL_ACTIVITY);
//            bundle.putString("batchNo", batchNo);
//            bundle.putString("batchTitle", batchTitle);
//            bundle.putString("pno", personListBean.getPno());
//            bundle.putString("maleId", maleID);
//            bundle.putString("femaleId", femaleID);
//            Utils.getInstance().startActivity(mActivity, PersonNewActivity.class, bundle);
//        });
//        mAdapter.setOnItemLongClickListener(s -> {
//            ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(this);
//            actionSheetDialogType.builder().setTitle("是否删除该用户").setCancelable(false).setCanceledOnTouchOutside(true);
//            actionSheetDialogType.addSheetItem("确定", R.color.green, () -> {
//                msg.remove(Integer.parseInt(s));
//                SpHelper.getInstance().setPersonListBean(batchNo, msg);
//                mAdapter.notifyDataSetChanged();
//            });
//            actionSheetDialogType.show();
//        });


    }

    @Override
    protected void initData() {
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.setType("application/vnd.ms-excel");
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        startActivityForResult(intent, Constant.GET_FILE);

        // right
        String[] batchUpName = getResources().getStringArray(R.array.batch_normal_name);
        String[] batchDownName = getResources().getStringArray(R.array.batch_sp_name);

        for (String s : batchUpName) {
            BatchNewBean map = new BatchNewBean(false);
            map.setName(s);
            batchUpList.add(map);
        }
        for (String s : batchDownName) {
            BatchNewBean map = new BatchNewBean(false);
            map.setName(s);
            batchDownList.add(map);
        }


        StaggeredGridLayoutManager layoutManagerUp = new StaggeredGridLayoutManager(6, StaggeredGridLayoutManager.VERTICAL);
        StaggeredGridLayoutManager layoutManagerDown = new StaggeredGridLayoutManager(6, StaggeredGridLayoutManager.VERTICAL);


        batchNewUp = new BatchNewAdapter(this, batchUpList, mustContain);
        personListChosenNormal.setLayoutManager(layoutManagerUp);
        personListChosenNormal.setAdapter(batchNewUp);

        batchNewDown = new BatchNewAdapter(this, batchDownList, null);
        personListChosenSp.setLayoutManager(layoutManagerDown);
        personListChosenSp.setAdapter(batchNewDown);

        batchNewUp.setOnItemClickListener((view, pos, isCheck) -> {

            for (int i = 0; i < batchUpList.size(); i++) {
                batchUpList.get(pos).setIsCheck(!isCheck);
            }
            batchNewUp.notifyDataSetChanged();

        });
        batchNewDown.setOnItemClickListener((view, pos, isCheck) -> {

            for (int i = 0; i < batchDownList.size(); i++) {
                batchDownList.get(pos).setIsCheck(!isCheck);
            }
            batchNewDown.notifyDataSetChanged();

        });
    }

    @Override
    protected void doOnDestroy() {

    }


    @Override
    protected void doOnResume() {
        msg.clear();
        List<PersonListBean> arrayList = getPersonListSelect(batchNo, null, null);
        if (arrayList != null) {
            msg.addAll(arrayList);
//            Collections.sort(msg);
            // 统计量体人数
            int all = msg.size();
            int i = 0;
            for (PersonListBean personListBean : msg) {
                if (personListBean.getLtDataDO() != null) {
                    if (!"".equals(personListBean.getLtDataDO().getTall())) {
                        i++;
                    }
                }
            }
        }
        mAdapter.notifyDataSetChanged();
//        //查看是否有量体部位列表§
//        String updress = SpHelper.getInstance().getString(Constant.CHOSEN_UPDERSS);
//        String downdress = SpHelper.getInstance().getString(Constant.CHOSEN_DOWNDERSS);
//        if ("".equals(updress) || "".equals(downdress)) {
//            showShortToast("没有选择量体部位");
//            Utils.getInstance().startActivity(this, BatchNewActivity.class, true);
//        }

    }

    @Override
    protected void doOnSaveInstanceState(Bundle savedInstanceState) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Constant.CONNECT_BLUE_TOOTH:
                    break;
                case Constant.GET_FILE:
                    Uri uri = data.getData();
                    String path = Utils.getInstance().getPath(this, uri);
                    String[] temp = path.split("\\.");
                    int i = temp.length - 1;
                    if ("xls".equals(temp[i]) || "XLS".equals(temp[i])) {
                        SpHelper.getInstance().setPersonList(batchNo, ExcelUtil.getInstance().importExcelData(path));
                        showShortToast("导入成功");
                        msg.clear();
                        List<PersonListBean> arrayList = SpHelper.getInstance().getPersonList(batchNo);
                        if (arrayList != null) {
                            msg.addAll(arrayList);
//                            Collections.sort(msg);
                            // 统计量体人数
                            int all = msg.size();
                            int n = 0;

                            for (PersonListBean personListBean : msg) {
                                if (personListBean.getLtDataDO() != null) {
                                    if (!"".equals(personListBean.getLtDataDO().getTall())) {
                                        n++;
                                    }
                                }
                            }

                        }
                        mAdapter.notifyDataSetChanged();

                    } else {
                        showShortToast("不是有效的Excel2003文件");
                    }
                    break;
                default:
                    break;
            }
        }
    }


    @Override
    public void responseError(int code, String msg) {

    }

    @Override
    public void requestFailure(Throwable t) {

    }

    @NonNull
    private List<PersonListBean> getPersonListSelect(String batchno, @Nullable String select1, @Nullable String select2) {
        List<PersonListBean> personList = new ArrayList<>(2);
        Map<String, Object> orgMap = Utils.getInstance().jso2map(SpHelper.getInstance().getString(batchno));
        orgKey = orgMap.keySet();
        if (select1 == null) {
            return SpHelper.getInstance().getPersonList(batchno);
        }
        Map<String, Object> depMap = Utils.getInstance().jso2map((String) orgMap.get(select1));
        if (select2 == null) {
            depKey = depMap.keySet();
            for (String keyDep : depKey) {
                ArrayList<String> personListMap = Utils.getInstance().jsa2list1((String) depMap.get(keyDep));
                for (String personString : personListMap) {
                    personList.add(new Gson().fromJson(personString, PersonListBean.class));
                }
            }
        } else {
            ArrayList<String> personListMap = Utils.getInstance().jsa2list1((String) depMap.get(select2));
            for (String personString : personListMap) {
                personList.add(new Gson().fromJson(personString, PersonListBean.class));
            }
        }
        return personList;
    }


    @OnClick(R.id.person_list_add_person)
    public void onPersonListAddPersonClicked() {
        dialogAdd.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.person_list_import)
    public void onPersonListimportClicked() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/vnd.ms-excel");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, Constant.GET_FILE);
    }


    @OnClick(R.id.person_list_submit)
    public void onPersonListSubmitClicked() {
    }

    @OnClick(R.id.dialog_add_num_del)
    public void onDialogAddNumDelClicked() {
        dialogAddNum.setText("");
    }

    @OnClick(R.id.dialog_add_name_del)
    public void onDialogAddNameDelClicked() {
        dialogAddName.setText("");
    }

    @OnClick(R.id.dialog_add_dep)
    public void onDialogAddDepClicked() {
    }

    @OnClick(R.id.dialog_add_cancel)
    public void onDialogAddCancelClicked() {
        dialogAdd.setVisibility(View.GONE);
    }

    @OnClick(R.id.dialog_add_submit)
    public void onDialogAddSubmitClicked() {
        PersonListBean personListBeanTemp = new PersonListBean();
        personListBeanTemp.setBatno(dialogAddNum.getText().toString().trim());
        personListBeanTemp.setDep(dialogAddDep.getText().toString().trim());
        personListBeanTemp.setName(dialogAddName.getText().toString().trim());
        personListBeanTemp.setSex(dialogAddSexId);
        msg.add(personListBeanTemp);
        SpHelper.getInstance().setPersonList(batchNo, msg);
        List<PersonListBean> arrayList = SpHelper.getInstance().getPersonList(batchNo);
        if (arrayList != null) {
//            Collections.sort(msg);
            // 统计量体人数
            int all = msg.size();
            int n = 0;

            for (PersonListBean personListBean : msg) {
                if (personListBean.getLtDataDO() != null) {
                    if (!"".equals(personListBean.getLtDataDO().getTall())) {
                        n++;
                    }
                }
            }

        }
        mAdapter.notifyDataSetChanged();
        dialogAdd.setVisibility(View.GONE);
    }

    @OnClick(R.id.dialog_add_sex)
    public void onDialogAddSexClicked() {
        ActionSheetDialog actionSheetDialogType = new ActionSheetDialog(this);
        actionSheetDialogType.builder().setCancelable(false).setCanceledOnTouchOutside(true);
        for (int i = 0; i < selectSex.length; i++) {
            String title = selectSex[i];
            int finalI = i;
            actionSheetDialogType.addSheetItem(title, R.color.green, () -> {
                dialogAddSex.setText(selectSex[finalI]);
                dialogAddSexId = finalI;
            });
        }
        actionSheetDialogType.show();
    }

    @OnClick(R.id.dialog_warning_cancel)
    public void onDialogWarningCancelClicked() {
        dialogWarning.setVisibility(View.GONE);
    }

    @OnClick(R.id.dialog_warning_submit)
    public void onDialogWarningSubmitClicked() {
        dialogWarning.setVisibility(View.GONE);
    }


    @OnTextChanged(value = R.id.dialog_add_num, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChangedNum(CharSequence s, int start, int before, int count) {
        if (dialogAddNum.getText().toString().trim().length() > 0) {
            dialogAddNumDel.setVisibility(View.VISIBLE);
        } else {
            dialogAddNumDel.setVisibility(View.GONE);
        }
    }

    @OnTextChanged(value = R.id.dialog_add_name, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChangedName(CharSequence s, int start, int before, int count) {
        if (dialogAddName.getText().toString().trim().length() > 0) {
            dialogAddNameDel.setVisibility(View.VISIBLE);
        } else {
            dialogAddNameDel.setVisibility(View.GONE);
        }
    }

    @OnCheckedChanged(R.id.person_list_check_normal)
    void onCheckBoxNormalCheckChange(boolean b) {
        for(BatchNewBean batchNewBean:batchUpList){
            batchNewBean.setIsCheck(b);
        }
        batchNewUp.notifyDataSetChanged();

    }
    @OnCheckedChanged(R.id.person_list_check_sp)
    void onCheckBoxSpCheckChange(boolean b) {
        for(BatchNewBean batchNewBean:batchDownList){
            batchNewBean.setIsCheck(b);
        }
        batchNewDown.notifyDataSetChanged();
    }
}
